import 'dart:convert';
import 'package:base_flutter/base_flutter.dart';
import 'package:dio/dio.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:ls_work/a_elder/models/waiting_right_entity.dart';
import 'package:ls_work/a_yyt/models/elder_time_line_entity.dart';
import 'package:ls_work/a_yyt/models/staff_group_entity.dart';
import 'package:ls_work/a_yyt/widget/client_time_cell.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/util/toast.dart';
import 'package:ls_work/widgets/click_item.dart';

import '../../util/flat_button.dart';



///评估审核
class PendingBizType1005 extends StatefulWidget {
  final WaitingRighInfo? info;
  final VoidCallback? callBack;
  PendingBizType1005({Key? key, this.info, this.callBack});
  @override
  _PendingBizType1005State createState() => _PendingBizType1005State();
}

class _PendingBizType1005State extends State<PendingBizType1005> {
  List<TimeLinesInfo> timeLineList = [];
  List<StaffGroupInfo> _nurseLevelList = [];
  int _groupValue = 1;
  String nurseLevel = '';
  int nurseLevelId = 0;

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      fectElderTimeLine();
      fectNurseLevel();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('评估审核'),
        elevation: 0.5,
      ),
      body: Container(
        height: ScreenUtil.getScreenH(context),
        width: ScreenUtil.getScreenW(context),
        padding: EdgeInsets.fromLTRB(30, 30, 30, 30),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text.rich(TextSpan(children: [
              TextSpan(
                text: '   长者：',
                style: TextStyles.textGray18,
              ),
              TextSpan(
                text: '${widget.info?.elderName ?? ''}',
                style: TextStyles.textDark18,
              ),
            ])),
            Gaps.vGap16,
            Text.rich(TextSpan(children: [
              TextSpan(
                text: '   评估类型：',
                style: TextStyles.textGray18,
              ),
              TextSpan(
                text: '${widget.info?.bizParams?.serviceItem ?? ''}',
                style: TextStyles.textDark18,
              ),
            ])),
            ClickItem(
              title: '*护理等级：',
              titleStyle: TextStyles.textGray18,
              content: '$nurseLevel',
              onTap: _bottomNurseLevelSheetAlert,
            ),
            Gaps.vGap16,
            Container(
              width: ScreenUtil.getScreenW(context),
              height: 50,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  // Text(
                  //   '审核结果：',
                  //   style: TextStyles.textDark18,
                  // ),
                  // Gaps.hGap16,
                  Flexible(
                    child: RadioListTile(
                      value: 1,
                      title: Text('审核通过'),
                      groupValue: _groupValue,
                      onChanged: (value) {
                        setState(() {
                          _groupValue = value!;
                        });
                      },
                    ),
                  ),
                  // Gaps.hGap16,
                  Flexible(
                    child: RadioListTile(
                      value: 0,
                      title: Text('返回修改'),
                      groupValue: _groupValue,
                      onChanged: (value) {
                        setState(() {
                          _groupValue = value!;
                        });
                      },
                    ),
                  ),
                ],
              ),
            ),
            Gaps.vGap50,
            Gaps.line,
            Expanded(
              child: ListView.builder(
                itemCount: timeLineList.length,
                itemBuilder: (_, index) {
                  return ClientTimeCell(
                    count: timeLineList.length,
                    info: timeLineList[index],
                  );
                },
              ),
            ),
            SizedBox(
              width: ScreenUtil.getScreenW(context),
              height: 50,
              child: FlatsButton(
                color: Colors.blue,
                highlightColor: Colors.blue[700]!,
                
                child: Text("提交"),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(25.0)),
                onPressed: _send,
              ),
            ),
          ],
        ),
      ),
    );
  }

  ///房型列表
  _bottomNurseLevelSheetAlert() {
    showModalBottomSheet(
        context: context,
        isScrollControlled: true,
        builder: (BuildContext context) {
          return Container(
            width: double.infinity,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: _nurseLevelList.map((f) {
                return ListTile(
                  title: Text(f.name??""),
                  onTap: () {
                    setState(() {
                      nurseLevel = f.name??"";
                      nurseLevelId = f.id??0;
                    });
                    Navigator.pop(context);
                  },
                );
              }).toList(),
            ),
          );
        });
  }

  void fectElderTimeLine() {
    var map = {
      'traceType': 130,
      'relationId': widget.info?.bizId,
      'customerId': widget.info?.customerId,
    };

    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post(HttpApi.elderTimeLine, data: map,options: PostRequest.urlencodedHeader)
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            TimeLineEntity model = TimeLineEntity.fromJson(map['data']);
            // print('🍎 - length - ${model.rows.length}');
            if ((model.rows??[]).length >= 0) {
              setState(() {
                timeLineList = model.rows??[];
              });
            }
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  void fectNurseLevel() {
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance.getDio().post(HttpApi.branchNurseLevel).then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            StaffGroupEntity model = StaffGroupEntity.fromJson(map);
            // print('🍎 - length - ${model.data.length}');
            if ((model.data??[]).length >= 0) {
              //   setState(() {
              _nurseLevelList = model.data??[];
              //   });
            }
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  ///提交
  void _send() {
    if (TextUtil.isEmpty(nurseLevel)) {
      Toast.show('请选择护理等级');
      return;
    }
    var map = {
      'id': widget.info?.bizId,
      'auditType': _groupValue,
      'nurseLevelId': nurseLevelId,
    };
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post(HttpApi.elderEvaluationSend,
            data: {'jsonStr': jsonEncode(map)},options: PostRequest.urlencodedHeader)
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          Toast.show(map["msg"]);
          if(widget.callBack!=null){
            widget.callBack!();
          }
          Navigator.pop(context);
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }
}
